/**
 * 
 */
package com.p2p.front.task;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.p2p.front.dal.model.LoanInfo;
import com.p2p.front.service.LoanInfoService;
import com.p2p.front.service.LoanVariationService;
import com.p2p.front.service.TenderAutoService;
import com.p2p.front.tender.FlowLoanTender;
import com.p2p.front.tender.NormalLoanTender;

/**
 * @author ruiqi
 *
 */
@Service("loanTimeOpenTask")
public class LoanTimeOpenTask extends BaseTask {

	@Resource
	private LoanInfoService loanInfoService;
	
	@Resource
	private LoanVariationService loanVariationService;
	
	@Resource
	private FlowLoanTender flowLoanTender;

	@Resource
	private NormalLoanTender normalLoanTender;
	
	@Resource
	private TenderAutoService tenderAutoService;
	
	@Scheduled( cron="0 0/1 * * * ? ")//每分钟一次
	public void findTimeOpenLoanSchedule(){
		boolean doTaskSynchronous = this.doTaskSynchronous(getBizKey(), 60);
		if(!doTaskSynchronous){
			return;
		}
		try {
			doBiz();
		} catch (Exception e) {
			logger.error("",e);
		}
		this.doRmoveTaskSynchronous(getBizKey());
	}

	@Override
	public String getBizKey() {
		String bizKey = "task_loanTimeOpenSchedule_";
		return bizKey;
	}
	
	public void doBiz(){
		logger.info("start scan can Tender loan");
		List<LoanInfo> list = loanVariationService.findCanTenderLoan();
		
		logger.info("find "+list.size()+" can Tender loan");
		for(LoanInfo loanInfo:list){
			int checkResult = loanInfo.checkStatusCanTender();
			if(checkResult==0){
				continue; 
			}
			boolean bool = loanInfoService.updateAuto(loanInfo.getLid(),1,loanInfo.getAuto());
			
			if(bool){
				logger.info("update auto 1 true,loanId="+loanInfo.getLid());
				loanVariationService.removetLoanInfoFromCache(loanInfo.getLid());
				try {
					tenderAutoService.startAutoQueue(loanInfo);
				} catch (Exception e) {
					logger.error("do auto queue error", e);
				}
				loanInfoService.updateAuto(loanInfo.getLid(),2,1);
				logger.info("update auto 2 true,loanId="+loanInfo.getLid());
				loanVariationService.removetLoanInfoFromCache(loanInfo.getLid());
			}
		}
		
	}
	
}
